#include "CrissCrossListener.h"

#include <stdio.h>
#include <iostream>

#include "database/TrackBase.h"
#include "io/HMMBuilder.h"
#include "io/BaseSaver.h"
#include "common.h"


CrissCrossListener::CrissCrossListener(std::string baseDir, CrissCross& crisscross):
																			cc(crisscross) {
	// Build recognizer
	const std::string baseSuffix(".lrn");
	std::string fileName = baseDir;
	std::vector<std::string> files = vector<string>();
	getdir(baseDir, files);

	// number of states
	const unsigned n = 5;
	// size of alphabet
	const unsigned m = 8;
	// max number of training iterations
	const unsigned maxIter = 100;
	// training delta
	const double delta = 0.001;
	// number of models
	double eps = 1.0e-10;
	
	std::cout << "base directory: " << baseDir << "\n";
	
	for (unsigned int i = 0; i < files.size(); i++) {
		if (files[i].size() >= 5 && files[i].substr(files[i].size() - 3) == "lrn") {
		    	std::cout << "add " << files[i] << "\n";
		    	std::string symbol = files[i].substr(0, files[i].size() - 4);
		    	std::cout << "symbol = " << symbol << "\n";
		    	rec.addModel(symbol, HMM());
		    	rec[symbol].initLRB(n, m, 0.5);
		    	rec[symbol].print();
		    	HMMBuilder::build((baseDir + files[i]).c_str(), rec[symbol]);
			rec[symbol].print();
		}
	}
}

void CrissCrossListener::isInterval(const LaserEvent& e) {
	printf("Listener notified about interval of time: %d.\n", e.time);
}
	
void CrissCrossListener::isTrack(const LaserEvent& e) {
	printf("Listener notified about Track.\n");
	
	Track track = e.track;
	
	// number of states
	const unsigned n = 5;
	// size of alphabet
	const unsigned m = 8;
	// max number of training iterations
	const unsigned maxIter = 100;
	// training delta
	const double delta = 0.001;
	// number of models
	double eps = 1.0e-10;
	
	// Recognize
	if (track.size() >= 5) {
		printf("track accepted.\n");
		Observation obs;
		track.convert(obs, m);
		std::string symbol = rec.recognize(obs);
		std::cout << "input recognized as " << symbol << "\n\n";
		Point center = track.getCenter();
    if (symbol == "x") {
	    cc.mouseClicked(center.x, center.y, 2);
    	cc.show();
    } else {
	    cc.mouseClicked(center.x, center.y, 1);
    	cc.show();
    }
	} else {
		printf("track rejeted\n");
	}
}

